package com.changgou.service.impl;

import com.changgou.pojo.FastDFSFile;
import com.changgou.service.FileService;
import com.changgou.utils.FastDFSClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author gentleman Ma
 * @Date created in 2020/2/15
 * @description
 * @Version 1.0
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String uploadFile(MultipartFile file) {
        log.info("[文件上传]File:{}",file);
        try {


            //1 获取文件原始名
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)){
                return null;
            }

            //2. 获取文件的扩展名
            int index = originalFilename.lastIndexOf(".");
            String extName = originalFilename.substring(index);


            //3 获取文件的内容
            byte[] content = file.getBytes();

            //4 封装上传文件对象
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename,content,extName);

            //5 执行上传
            String[] uploadResult  = FastDFSClient.upload(fastDFSFile);
            //获取组名
            String groupName = uploadResult[0];
            //获取文件存储路径
            String remoteFileName = uploadResult[1];

            //6 拿到上传结果,拼接URL
            String url = FastDFSClient.getTrackerUrl()+ groupName+"/"+remoteFileName;

            log.info("[上传成功文件地址]url:{}",url);
            return url;
        }catch (IOException e){
            e.printStackTrace();
            log.error("[上传文件失败]");
            return null;
        }

    }
}
